package org.smart4j.framework.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * description: 流操作工具类  
 * @version v1.0
 * @author w
 * @date 2018年9月1日下午10:34:31
 */
public class StreamUtil {

	private static final Logger logger =	LoggerFactory.getLogger(StreamUtil.class);
	
	/**
	 * description: 从输入流中获取字符串
	 * @param input
	 * @return
	 * String
	 * @version v1.0
	 * @author w
	 * @date 2018年9月1日 下午10:37:23
	 */
	public static String getString(InputStream input){
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(input));
		String line ;
		try {
			while((line=reader.readLine())!= null){
				sb.append(line);
			}
		} catch (IOException e) {
			logger.error("get string failure ",e);
			throw new RuntimeException(e);
		}
		return sb.toString();
	}
	
	/**
	 * description: 文件复制 --- 输入流到输出流
	 * @param inputStream
	 * @param outputStream
	 * @return void
	 * @version v1.0
	 * @author w
	 * @date 2018年10月22日 下午9:43:58
	 */
	public static void copyStream(InputStream inputStream , OutputStream outputStream){
		int length = 0 ;
		byte[] buffer = new byte[4 * 1024];
		try {
			while((length = inputStream.read(buffer)) != -1){
				outputStream.write(buffer, 0, length);
				outputStream.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(null != outputStream){
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null != inputStream){
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	} // end copyStream
	
	
}
